﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Foundry.Graphics
{
    public class Framebuffer : IHandle, IDisposable
    {
        public int Handle { get; private set; }
        public bool Disposed { get; private set; }
        public event EventHandler Disposing;

        public Framebuffer()
        {
            GraphicsContext.Assert();
            int new_handle;
            GL.GenFramebuffers(1, out new_handle);
            Handle = new_handle;
        }

        public void Bind(Renderbuffer target, FramebufferAttachment attachment)
        {
            MakeCurrent();
            GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachment, RenderbufferTarget.Renderbuffer, target.Handle);
            MakeNullCurrent();
        }
        public void Bind(Texture texture, FramebufferAttachment attachment)
        {
            MakeCurrent();
            GL.FramebufferTexture(FramebufferTarget.Framebuffer, attachment, texture.Handle, 0);
            MakeNullCurrent();
        }

        public void Unbind(FramebufferAttachment attachment)
        {
            MakeCurrent();
            GL.FramebufferTexture(FramebufferTarget.Framebuffer, attachment, 0, 0);
            MakeNullCurrent();
        }

        public void MakeCurrent()
        {
            if (Disposed)
                throw new ObjectDisposedException(GetType().FullName);

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, Handle);
        }
        public void MakeNullCurrent()
        {
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
        }
        public void Dispose()
        {
            if (Disposed)
                throw new ObjectDisposedException(GetType().FullName);
            if (Disposing != null)
                Disposing(this, EventArgs.Empty);
            GL.DeleteFramebuffers(1, new int[] { Handle });
            Handle = 0;
            Disposed = true;
        }
    }
}
